package cn.jeefast.rest.controller;

import cn.jeefast.common.entity.*;
import cn.jeefast.common.utils.R;
import cn.jeefast.rest.annotation.AuthIgnore;
import cn.jeefast.rest.entity.TbUser;
import cn.jeefast.rest.service.*;
import cn.jeefast.rest.util.ExportExcelDownFee;
import cn.jeefast.rest.util.ExportExcelUtils;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.formula.functions.T;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.activation.DataHandler;
import javax.activation.URLDataSource;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/api")
public class ExportPatientController {

    /**
     * 日志
     */
    private static final Logger log = LoggerFactory.getLogger(ExportPatientController.class);

    @Autowired
    private MbPatientService patientService;
    @Autowired
    private MbDoctorService doctorService;
    @Autowired
    private MbDialysisWayService dialysisWayService;
    @Autowired
    private MbResearchService researchService;
    @Autowired
    private MbTreatmentPlanService mbTreatmentPlanService;
    @Autowired
    private MbResearchStepService researchStepService;
    @Autowired
    private MbResearchDataService researchDataService;
    @Autowired
    private MbResearchSetpDataDetailService mbResearchSetpDataDetailService;
    @Autowired
    private TbUserService userService;

    /**
     * 通用导出
     * @param response
     * @param ids
     * @return
     */
    @RequestMapping("/ExpExcel")
    @AuthIgnore
    public void export1(HttpServletResponse response,String ids){
        log.info("{}：开始通用导出，ids：{}",Thread.currentThread().getId(),ids);

        String[] split = ids.split(",");
        long[] idss = (long[]) ConvertUtils.convert(split,long.class);
        JSONObject result = new JSONObject();
//
//        List<Map<Integer, Object>> maps = new ArrayList<>();
        MbPatient mbPatient = patientService.selectById(idss[0]);
        String str = syncHeader(mbPatient.getResId());
        List<Map> maps = expData(idss);
        if (maps.size() != 0)
        {
            try
            {
                String title = "导出";
                String[] rowsName = str.split(",");
                List<Object[]> dataList = new ArrayList<Object[]>();
                Object[] objs = null;
                for (int i = 0; i < maps.size(); i++)
                {
                    objs = new Object[rowsName.length];
                    objs[0] = "";   //序列
                        for (int h=1;h<=maps.get(i).size();h++) {
                            objs[h] = maps.get(i).get(h-1);   //序列
                    }
                    dataList.add(objs);
                }
                ExportExcelDownFee ex = new ExportExcelDownFee(title, rowsName, dataList, response);
                ex.exportData();
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
        try {
            result.put("flag", "true");
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(result.toString());
//        return result;
    }

    /**
     * 邮件导出
     * @param mail
     * @return
     */
    @RequestMapping("/export/list")
    private R mailtoDoc(String mail,Long[] ids){
        log.info("{}：开始邮件导出 \n ids：{} \n mail:{}",Thread.currentThread().getId(),ids,mail);
        //获取研究组，并进行分类
        List<Long> longs = patientService.selectResIdByPatId(ids);
        List<long[]> result = new ArrayList<>();
        for (Long resId:longs) {
            String str = "";
            for (Long id:ids) {
                MbPatient mbPatient = patientService.selectById(id);
                if(mbPatient.getResId()==resId){
                    //如果属于该组，那么就存入字符串再转成Long[]
                    str += id.toString()+",";
                }
            }
            //去掉最后一个,
            if(str.substring(str.length()-1,str.length()).equals(",")){
                str.substring(0,str.length()-1);
            }
            //转为Long[]集合
            String[] split = str.split(",");
            long[] idss = (long[]) ConvertUtils.convert(split,long.class);
            result.add(idss);
        }
        //传入邮件方法
        try {
            mail(mail,result);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return R.ok();
    }



    private R mail(String mail ,List<long[]> ids) throws Exception{
        log.info("{}：准备发送邮件 \n ids：{} \n mail:{}",Thread.currentThread().getId(),ids,mail);
        System.out.println("sendMailServlet-----start2");

        //1.创建邮件对象
        Properties properties = new Properties();
        properties.put("mail.smtp.host", "smtp.163.com"); // 指定SMTP服务器
        properties.put("mail.smtp.auth", "true"); // 指定是否需要SMTP验证
        properties.put("mail.smtp.port", "465");
        Session session = Session.getInstance(properties);
        MimeMessage message =new MimeMessage(session);

        /*2.设置发件人
         * 其中 InternetAddress 的三个参数分别为: 邮箱, 显示的昵称(只用于显示, 没有特别的要求), 昵称的字符集编码
         * */
        message.setFrom(new InternetAddress("anewhen@163.com","anewhen","UTF-8"));
        /*3.设置收件人
        To收件人   CC 抄送  BCC密送*/
        message.setRecipient(MimeMessage.RecipientType.TO,new InternetAddress(mail,"manbing","UTF-8"));
//        message.addRecipient(MimeMessage.RecipientType.TO,new InternetAddress("17862****9@qq.com","xiuhong","UTF-8"));

        /*4.设置标题*/
        message.setSubject("附件导出下载","UTF-8");
        //message.setContent("Test Content:这是一封测试邮件...","text/html;charset=UTF-8");

        /*5.设置邮件正文*/

        //一个Multipart对象包含一个或多个bodypart对象，组成邮件正文
        MimeMultipart multipart = new MimeMultipart();


        //创建文本节点
        MimeBodyPart text = new MimeBodyPart();
        text.setContent("请在附件中下载相关报表。及时下载，以免失效","text/html;charset=UTF-8");

        for (int i=0;i<ids.size();i++) {
            if (ids.size() >= 1) {
                if (((long[]) ids.get(i)) != null && ((long[]) ids.get(i)).length != 0) {
                    long[] longs = ids.get(i);
                    String longStr = "";
                    for (int j = 0; j < longs.length; j++) {
                        if (j == 0) {
                            longStr = longs[j] + "";
                        } else {
                            longStr += "," + longs[j];
                        }
                    }
                    URL url1 = new URL("http://localhost:7081/jeefast-rest/api/ExpExcel?token=admin&ids=" + longStr);
                    MimeBodyPart file1 = new MimeBodyPart();
                    DataHandler dataHandler = new DataHandler(new URLDataSource(url1));
                    file1.setDataHandler(dataHandler);
                    //根据第一个患者ID获取研究组名称
                    MbPatient mbPatient = patientService.selectById(longs[0]);
                    MbResearch mbResearch = researchService.selectById(mbPatient.getResId());
                    //设置文件名称
                    file1.setFileName(MimeUtility.encodeText(mbResearch.getResName() + ".xls"));
                    multipart.addBodyPart(file1);
                }
            }
        }

        //将文本和图片添加到multipart
        multipart.addBodyPart(text);

        multipart.setSubType("mixed");//混合关系

        message.setContent(multipart);
        message.setSentDate(new Date());
        message.saveChanges();
        Transport transport = session.getTransport("smtp");
        transport.connect("smtp.163.com","anewhen@163.com","Aa01Bb02");
        transport.sendMessage(message,message.getAllRecipients());
        transport.close();
        Boolean isFlag = true;
//        logger.info(Calendar.getInstance().getTime()+" : # Send mail to "+" success #");
        System.out.println("sendMailServlet-----end2");
        log.info("{}：邮件导出结束 ",Thread.currentThread().getId());
        return R.ok();
    }

    public List<Map> expData(long[] ids){
        //根据ID获取用户所在研究组
        List<Map> result = new ArrayList<>();
        for (Long id:ids) {
            MbPatient mbPatient = patientService.selectById(id);
            //循环查询患者主要信息
            List<Object> info =  new ArrayList<>();
            info.add(mbPatient.getId());
            info.add(mbPatient.getPatName());
            TbUser mbDoctor = userService.selectById(mbPatient.getDocId());
            info.add(mbDoctor.getUsername());
            MbDialysisWay mbDialysisWay = dialysisWayService.selectById(mbPatient.getDwId());
            //透析方式
            info.add(mbDialysisWay==null?"":mbDialysisWay.getTitle());
            //诊断
            info.add(mbPatient.getDiagnosis());
            MbResearch mbResearch = researchService.selectById(mbPatient.getResId());
            //研究组
            info.add(mbResearch.getResName());
//            MbTreatmentPlan mbTreatmentPlan = mbTreatmentPlanService.selectById(mbPatient.getTpId());
            //治疗方案
            String[] tpIds = mbPatient.getTpId().split(",");
            //酮酸治疗
            boolean flag1 = ArrayUtils.contains(tpIds, "1");
            if(flag1){
                info.add("是");
            }else{
                info.add("否");
            }
            //费瑞卡处方量
//            //酮酸治疗 ID1
//            info.add(mbPatient.getTpId()==1?"是":"否");
            //费瑞卡处方量
            //标记量，如果出现非1，则标记为true,
            Boolean flag2 = false;
            for (String tpid:tpIds) {
                if(!tpid.equals("1")){
                    MbTreatmentPlan mbTreatmentPlan = mbTreatmentPlanService.selectById(Long.parseLong(tpid));
                    info.add(mbTreatmentPlan.getTitle()+" "+mbTreatmentPlan.getUnit());
                    flag2 = true;
                }
            }
            if(!flag2){
                info.add("否");
            }
            //身高
            info.add(mbPatient.getTall());
            //循环添加周期数据
            //根据研究组，获取所有的研究阶段
            EntityWrapper ew = new EntityWrapper();
            ew.eq("res_id",mbPatient.getResId());
            List<MbResearchStep> list = researchStepService.selectList(ew);
            for (MbResearchStep li:list) {
                EntityWrapper ew1 = new EntityWrapper();
                ew1.eq("res_step_id",li.getStepId());
                ew1.eq("patient_id",mbPatient.getId());
                List<MbResearchData> list1 = researchDataService.selectList(ew1);
                MbResearchData mbResearchData = list1.get(0);
                info.add(mbResearchData.getAiWeight());
                info.add(mbResearchData.getAiGrip());
                EntityWrapper ewt0 = new EntityWrapper();
                ewt0.eq("data_detail_id",mbResearchData.getDataId());
                List<MbResearchSetpDataDetail> list2 = mbResearchSetpDataDetailService.selectList(ewt0);
                for (MbResearchSetpDataDetail mrdd:list2) {
                    info.add(mrdd.getDdValue());
                }
            }
            Map m = new HashMap();
            for (int i=0;i<info.size();i++){
                m.put(i,info.get(i));
            }
            result.add(m);
        }
        //打印result
        System.out.println("打印result"+result);
        return result;
    }

    public String syncHeader(Long researchId){
        //根据研究阶段ID 查询研究阶段
        EntityWrapper ew = new EntityWrapper();
        ew.eq("res_id",researchId);
        List<MbResearchStep> list = researchStepService.selectList(ew);
        String listStr = "";
        for (MbResearchStep mrs:list) {
            listStr += mrs.getStepName()+",";
        }
        if(listStr.length()<=0){
            return null;
        }
        if(listStr.substring(listStr.length()-1,listStr.length()).equals(",")){
            listStr.substring(0,listStr.length()-1);
        }
        //拼接表头
        String str = "序列,编号,姓名,医生,透析方式,诊断,研究组,酮酸治疗,费瑞卡处方量,身高,";
        String[] sts = listStr.split(",");
        for (String st:sts) {
            str += st+"-体重,";
            str += st+"-握力,";
            //1:ALB 2:CPR 3:TCHO 4:TG 5:LDL-C 6:HDL-C 7:SCR 8:BUN 9:P
            str += st+"-ALB,";
            str += st+"-CRP,";
            str += st+"-TCHO,";
            str += st+"-TG,";
            str += st+"-LDL-C,";
            str += st+"-HDL-C,";
            str += st+"-SCR,";
            str += st+"-BUN,";
            str += st+"-P,";
        }
        if(str.substring(str.length()-1,str.length()).equals(",")){
            str.substring(0,str.length()-1);
        }
        return str;
    }
}
